﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;

using SharedGenomics.Core;

namespace SharedGenomics.Core.Configuration
{
    public class ContainerConfigurationStrategyChain
    {
        private readonly ICollection<IContainerConfigurationStrategy> _configStrategies;

        public ContainerConfigurationStrategyChain()
        {
            this._configStrategies = new LinkedList<IContainerConfigurationStrategy>();
        }

        public void AddStrategy<TStrategy>() where TStrategy : IContainerConfigurationStrategy, new()
        {
            this.AddStrategy(new TStrategy());
        }

        public void AddStrategy(IContainerConfigurationStrategy strategy)
        {
            strategy.ThrowIfNull("strategy");
            this._configStrategies.Add(strategy);
        }

        public IUnityContainer CreateContainer(IConfigurationReader configReader)
        {
            configReader.ThrowIfNull("configReader");

            IUnityContainer container = new UnityContainer();
            ContainerConfigurationContext context = new ContainerConfigurationContext(configReader, container);

            foreach (var configStrategy in this._configStrategies)
            {
                configStrategy.Configure(context);
            }

            return context.Container;
        }
    }
}
